package com.nisiken.aws.ses;

import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AWSJavaMailTransport;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient;
import com.amazonaws.services.simpleemail.model.ListVerifiedEmailAddressesResult;
import com.amazonaws.services.simpleemail.model.SendEmailRequest;
import com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest;

public class SESUtils {

	public SESUtils() {
		// TODO Auto-generated constructor stub
	}

	public static void sendMail(String from, List<String> tos, String subject, String body) {
		AWSCredentials credentials = new ClasspathPropertiesFileCredentialsProvider().getCredentials();
		AmazonSimpleEmailService ses = new AmazonSimpleEmailServiceClient(credentials);
		Region usWest2 = Region.getRegion(Regions.US_EAST_1);
		ses.setRegion(usWest2);

		/*
		 * Setup JavaMail to use the Amazon Simple Email Service by specifying
		 * the "aws" protocol.
		 */
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "aws");

        /*
         * Setting mail.aws.user and mail.aws.password are optional. Setting
         * these will allow you to send mail using the static transport send()
         * convince method.  It will also allow you to call connect() with no
         * parameters. Otherwise, a user name and password must be specified
         * in connect.
         */
        props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId());
        props.setProperty("mail.aws.password", credentials.getAWSSecretKey());

        //Session session = Session.getInstance(props);
        Session session = Session.getDefaultInstance(props);
        
        try {
        	// Create a new Message
        	Message msg = new MimeMessage(session);
        	msg.setFrom(new InternetAddress(from));
        	for (String to : tos) {
        		msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        	}
        	msg.setSubject(subject);
        	msg.setText(body);
        	msg.saveChanges();

        	// Reuse one Transport object for sending all your messages
        	// for better performance
        	Transport t = new AWSJavaMailTransport(session, null);
        	t.connect();
        	t.sendMessage(msg, null);

        	// Close your transport when you're completely done sending
        	// all your messages
        	t.close();

        } catch (AddressException e) {
            e.printStackTrace();
            System.out.println("Caught an AddressException, which means one or more of your "
                    + "addresses are improperly formatted.");
            throw new RuntimeException(e);
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("Caught a MessagingException, which means that there was a "
                    + "problem sending your message to Amazon's E-mail Service check the "
                    + "stack trace for more information.");
            throw new RuntimeException(e);
        }
	}
	
	public static void verifyAddress(String address) {
		AWSCredentials credentials = new ClasspathPropertiesFileCredentialsProvider().getCredentials();
		AmazonSimpleEmailService ses = new AmazonSimpleEmailServiceClient(credentials);
		Region usWest2 = Region.getRegion(Regions.US_EAST_1);
		ses.setRegion(usWest2);
		
		ListVerifiedEmailAddressesResult verifiedEmails = ses.listVerifiedEmailAddresses();
        if (verifiedEmails.getVerifiedEmailAddresses().contains(address)) return;

        ses.verifyEmailAddress(new VerifyEmailAddressRequest().withEmailAddress(address));
	}

	/**
	 * send mail for schedule
	 * 
	 * @param firstFireDate
	 * @param intervalTimeInMille
	 * @param loopCnt : -1 -> closedloop
	 * @param from
	 * @param to
	 * @param subject
	 * @param body
	 * @return timer
	 */
	public static Timer sendScheduleMail(final Date firstFireDate, final int intervalTimeInMille,
			final String from, final List<String> to, final String subject, final String body) {
		
		TimerTask sendMailTask = new TimerTask() {
			@Override
			public void run() {
				sendMail(from, to, subject, body);
			}
		};
		
		Timer timer = new Timer();
		timer.schedule(sendMailTask, firstFireDate, intervalTimeInMille);
		
		return timer;
	}
}
